<template>
  <div style="display: flex;flex-direction: row;height:100%;" class="wood">
    <!-- 左侧话题列表和主界面输入框 -->
    <div class="topic-list" style="flex: 3; position: relative;">
      <div class="back-btn" @click="goBack">← {{tag}}区话题</div>
      <div class="page-container">
        <h2> </h2>
      </div>
      <!-- 为聊天列表添加固定高度和滚动条 -->
      <div v-if="isDataLoaded" class="chat-list" style="height: 400px; overflow-y: auto;"> 
        <div 
          v-for="(topic, index) in topiclist.topic" 
          :key="topic.id || index" 
          class="chat-item"
          @click="showTopicDetail(topiclist.topic[index])"
        >
          <img class="avatar" :src="getPath(topiclist.userfeild[index])">
          <div class="chat-info">
            <!-- 添加数据检查 -->
            <div class="chat-user">{{ topiclist.username[index]}} - {{topic.createTime ? formatTime(topic.createTime) : '未知时间'}}</div>
            <div class="chat-content">{{ topic.content || '' }}</div>
            <div class="chat-interact"style="display: flex;flex-direction: row;">
			  <div style="width: 25px;"><Like1 @click.stop="likeTopic(index)" v-if="!topiclist.topic[index].islike" /> <Like2 v-else/></div>
			  <div style="width: 30px;font-size: 1rem;">{{ topic.likecount || 0 }}</div>
			  <div style="width: 25px;padding: 2px;"><Comment/></div>
			  <div style="width: 30px;font-size: 1rem;"> {{ topiclist.topiccommentnum[index] || 0 }}</div>
            </div>
          </div>
        </div>
      </div>
      <!-- 主界面输入框 -->
      <ChatInput @send="handleMainMessageSend" />
      <!-- 点击左侧关闭详情 -->
      <div class="close-area" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 10;" v-if="selectedTopic" @click="closeTopicDetail"></div>
    </div>
    <!-- 右侧话题详情和评论区 -->
    <div class="topic-detail" style="flex: 5; display: flex; flex-direction: column; padding: 20px; border-left: 1px solid #eee; position: relative; z-index: 20;" v-if="selectedTopic">
      <div class="detail-header">
        <img class="avatar" :src="selectedTopic.avatar ">
        <div class="chat-info">
          <div class="chat-user">{{ selectedTopic.user }} - {{ selectedTopic.createTime ? formatTime(selectedTopic.createTime) : '未知时间' }}</div>
          <div class="chat-content">{{ selectedTopic.content }}</div>
          <div class="chat-interact" style="display: flex;flex-direction: row;">
            <div style="width: 25px;"><Like1 v-if="!selectedTopic.islike" @click="likeThisTopic()"/> <Like2 v-else/></div>
			<div style="width: 30px;font-size: 1rem;">{{ selectedTopic.likecount || 0 }}</div>
            <div style="width: 25px;padding: 2px;"><Comment/></div>
			<div style="width: 30px;font-size: 1rem;"> {{ selectedTopic.commentsCount || 0 }}</div>
          </div>
        </div>
      </div>
      <div class="comments-list" style="height: 300px; overflow-y: auto;"> <!-- 为评论列表添加固定高度和滚动条 -->
        <h3>评论列表</h3>
        <div 
          v-for="(comment, commentIndex) in selectedTopic.comments || []" 
          :key="comment.id || commentIndex" 
          class="comment-item"
        >
          <img class="avatar" :src="comment.useravatar ">
          <div class="chat-info">
            <div class="chat-user">{{ comment.username }} - {{ comment.createTime ? formatTime(comment.createTime) : '未知时间' }}</div>
            <div class="chat-content">{{ comment.content }}</div>
          </div>
        </div>
      </div>
      <!-- 详情页输入框 -->
      <div class="detail-chat-input">
        <input v-model="detailInputValue" class="input-box" placeholder="请输入评论内容" @keyup.enter="sendDetailMessage" />
        <button class="send-btn" @click="sendDetailMessage">发送</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch, watchEffect } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getPath } from '@/util';
import { getCookieForObject } from '@/util';
import { get, post } from '@/plugins/axios';
import { ElMessage } from 'element-plus';
import { _axios } from '@/plugins/axios';
import { onBeforeRouteUpdate } from 'vue-router';
import ChatInput from './chatinput.vue'
import Like1 from './img/like1'
import Like2 from './img/like2'
import Comment from './img/comment'

const route = useRoute();
const router = useRouter();
const tag = ref('');
const defaultAvatar = 'https://i.pravatar.cc/48?u=default'; // 默认头像

const topiclist = reactive({
  topic: [],
  userfeild: [],
  username: [],
  topiccomment: [],
  topiccommentnum: []
});

const isDataLoaded = ref(false); // 添加加载状态标志
const selectedTopic = ref(null);
const detailInputValue = ref('');

function getUserId() {
  const userinfo = getCookieForObject('user');
  return userinfo?.id;
}

function getUserName() {
  const userinfo = getCookieForObject('user');
  return userinfo?.username;
}

function getUserFile() {
  const userinfo = getCookieForObject('user');
  return getPath(userinfo?.file);
}

async function getTopicByTag() {
  try {
    const response = await _axios.get("/topic/groups", { params: { title: route.query.TopicId } });
    // console.dir(response);
    
    // 重置数据
    topiclist.topic = [];
    topiclist.userfeild = [];
    topiclist.username = [];
    topiclist.topiccomment = [];
    topiclist.topiccommentnum = [];
    
    topiclist.topic = response.data;
    
    // 创建一个映射对象来存储每个话题ID对应的索引位置
    const topicIdIndexMap = response.data.reduce((map, topic, index) => {
      map[topic.id] = index;
      return map;
    }, {});
    
    // 处理用户信息请求
    const userPromises = response.data.map(topic => {
      return getUserById(topic.userId).then(userInfo => {
        // 获取话题在数组中的索引
		// console.dir(userInfo);
        const index = topicIdIndexMap[topic.id];
        if (index !== undefined) {
          // 确保在正确的索引位置设置用户信息
          topiclist.userfeild[index] = userInfo.content.avatar ;
          topiclist.username[index] = userInfo.content.username ;
        }
        return userInfo;
      });
    });
    
    // 处理评论请求
    const commentPromises = response.data.map(topic => {
      return getTopicComment(topic.id).then(comments => {
        // 获取话题在数组中的索引
        const index = topicIdIndexMap[topic.id];
        if (index !== undefined) {
          // 确保在正确的索引位置设置评论信息
          topiclist.topiccomment[index] = comments || [];
          topiclist.topiccommentnum[index] = comments?.length || 0;
		  topiclist.topic[index].islike=false;
          
          // 直接将评论数据关联到对应的话题对象
          topiclist.topic[index].comments = comments || [];
          topiclist.topic[index].commentsCount = comments?.length || 0;
        }
        return comments;
      });
    });
    
    // 等待所有用户信息和评论信息加载完成
    await Promise.all([...userPromises, ...commentPromises]);
    
    isDataLoaded.value = true; // 所有数据加载完成后更新标志
    
    // console.dir(topiclist);
    // console.dir(topiclist.topiccomment);
    // console.dir(topiclist.topiccommentnum);
  } catch (error) {
    console.error('获取话题列表失败:', error);
    ElMessage.error('获取话题列表失败，请稍后重试');
  }
}

async function getUserById(Id) {
  try {
    const content = await _axios.get('/tUser/getById2', { params:{ id: Id }});
	
    return content.data;
  } catch (error) {
    console.error('获取用户信息失败:', error);
    return null;
  }
}

async function getTopicComment(Id) {
  try {
    const response = await _axios.get("/topicComment/list", { params: { topicId: Id } });
    return response.data;
  } catch (error) {
    console.error('获取话题评论失败:', error);
    return null;
  }
}

function getTag() {
  switch (route.query.TopicId) {
    case "1": tag.value = "萌宠空间"; break;
    case "2": tag.value = "以旧换新"; break;
    case '3': tag.value = "家用儿女"; break;
    case '4': tag.value = "二手物品"; break;
    case '5': tag.value = "社区治理"; break;
    default: tag.value = "未知分类"; break;
  }
  getTopicByTag();
}

onMounted(() => {
  getTag();
  
  // 监听路由变化，重新加载数据
  onBeforeRouteUpdate((to) => {
    if (to.query.TopicId !== route.query.TopicId) {
      isDataLoaded.value = false;
      getTag();
    }
  });
});

// 完善时间格式化函数
function formatTime(time: string | number | Date) {
  if (!time) return '未知时间';
  
  // 处理不同格式的时间输入
  const date = new Date(time);
  
  if (isNaN(date.getTime())) {
    // 尝试解析字符串格式
    try {
      return new Date(time).toLocaleString();
    } catch (e) {
      return time.toString();
    }
  }
  
  // 格式化日期为本地格式
  return date.toLocaleString();
}

async function getCommentUser(){
	const UserIdIndexMap = selectedTopic.value.comments.reduce((map, topic, index) => {
	  map[topic.id] = index;
	  return map;
	}, {});
	
	// 处理用户信息请求
	const user2Promises = selectedTopic.value.comments.map(topic => {
	  return getUserById(topic.userId).then(userInfo => {
	    // 获取话题在数组中的索引
		 console.dir(userInfo);
	    const index = UserIdIndexMap[topic.id];
	    if (index !== undefined) {
	      // 确保在正确的索引位置设置用户信息
	      selectedTopic.value.comments[index].useravatar=getPath(userInfo.content.avatar);
	      selectedTopic.value.comments[index].username = userInfo.content.username ;
	    }
	    return null;
	  });
	});
	
	// 等待所有用户信息和评论信息加载完成
	await Promise.all([...user2Promises]);
	
	isDataLoaded.value = true; // 所有数据加载完成后更新标志
}

function showTopicDetail(topic) {
  // 创建一个深拷贝，避免直接修改原始数据
  selectedTopic.value = topic;
  console.dir(topic)
  console.dir(selectedTopic.value)
  // 确保有必要的属性
  if (!selectedTopic.value.comments) {
    selectedTopic.value.comments = [];
  }
  
  if (!selectedTopic.value.commentsCount) {
    selectedTopic.value.commentsCount = selectedTopic.value.comments.length;
  }
  getCommentUser()
  // 查找话题在原始数组中的索引
  const topicIndex = topiclist.topic.findIndex(t => t.id === selectedTopic.value.id);
  console.dir(topicIndex)
  
  // 添加用户信息
  if (topicIndex !== -1) {
    selectedTopic.value.user = topiclist.username[topicIndex];
    selectedTopic.value.avatar = getPath(topiclist.userfeild[topicIndex]);
  } else {
    // 如果找不到索引，使用默认值
    selectedTopic.value.user = '未知用户';
    selectedTopic.value.avatar = defaultAvatar;
  }
  console.dir(selectedTopic.value)
}

function likeTopic(index){
	topiclist.topic[index].islike=true;
	topiclist.topic[index].likecount++;
	post("/topic/like",{id:topiclist.topic[index].id},content=>{
		console.dir(1111111111)
	});
}

function likeThisTopic(){
	const topicIndex = topiclist.topic.findIndex(t => t.id === selectedTopic.value.id);
	likeTopic(topicIndex)
	selectedTopic.value.islike=true;
	selectedTopic.value.likecount++;
}
// 完善后的 handleMainMessageSend 函数
const handleMainMessageSend = (msg: string) => {
  if (msg.trim()) {
	  post("/topic/add",{userId:getUserId(),title:route.query.TopicId,content:msg},content=>{
		  console.dir(1111111111)
		console.dir(content);
		// 将新消息添加到消息列表的顶部
		topiclist.topic.unshift(content);
		topiclist.userfeild.unshift(getUserFile());
		topiclist.username.unshift(getUserName());
		topiclist.topiccomment.unshift([]);
		topiclist.topiccommentnum.unshift(0);
	})
    
    
  }
};

function sendDetailMessage() {
  if (detailInputValue.value.trim()) {
    if (selectedTopic.value) {
		
		post("/topicComment/add",{topicId:selectedTopic.value.id,userId:getUserId(),content:detailInputValue.value},content=>{
			console.dir(content);
			// 将新消息添加到消息列表的顶部			
			selectedTopic.value.comments.push(content);
	        getCommentUser()
			selectedTopic.value.commentsCount++;
			// 更新原始数据中的评论数
			const topicIndex = topiclist.topic.findIndex(t => t.id === selectedTopic.value.id);
			if (topicIndex !== -1) {
			  topiclist.topiccomment[topicIndex]=selectedTopic.value.comments;
			  topiclist.topiccommentnum[topicIndex] = selectedTopic.value.commentsCount;
			  console.dir(topicIndex);
			  console.dir(topiclist.topiccomment[topicIndex]);
			  console.dir(topiclist.topiccommentnum[topicIndex]);
			}
		})
		
      
      detailInputValue.value = '';

    }
  }
}

function closeTopicDetail() {
  selectedTopic.value = null;
  console.dir(topiclist.topiccomment);
}

function goBack() {
  router.replace('/chat');
}

// 使用 watchEffect 来观察 topiclist 的变化
watchEffect(() => {
  if (isDataLoaded.value) {
    console.log('Data is loaded, component should re-render');
    
    // DOM更新后执行的操作
    nextTick(() => {
      console.log('DOM has been updated');
    });
  }
});

// 监听 selectedTopic 变化
watch(selectedTopic, (newVal) => {
  console.log('Selected topic changed:', newVal);
});
</script>

<style scoped lang="scss">
.wood {
  background-color: #fff5e9;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.topic-list {
  padding: 20px;
  background-color: #fff5e9;
  border-right: 1px solid #eee;
}

.back-btn {
  cursor: pointer;
  font-size: 2rem;
  margin-bottom: 20px;
  color: #ab6207;
}

.chat-list {
  margin-bottom: 60px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 20px;
}

.chat-item {
  background-color: #fffdfb;
  padding: 20px;
  border-radius: 10px;
  cursor: pointer;
  display: flex;
  align-items: flex-start;
  transition: all 0.3s ease;
}

.chat-item:hover {
  background-color: #f8dcbb;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  margin-right: 12px;
  border: 2px solid #eee;
  object-fit: cover;
}

.chat-user {
  font-weight: bold;
  margin-bottom: 5px;
}

.chat-content {
  margin-bottom: 5px;
  min-height: 40px; /* 设置最小高度 */
  max-height: 80px; /* 设置最大高度 */
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 显示的行数 */
  -webkit-box-orient: vertical;
}

.chat-interact {
  color: #666;
  font-size: 12px;
}

.topic-detail {
  padding: 20px;
  background-color: #fff;
  box-shadow: -4px 0 8px rgba(0, 0, 0, 0.05);
  overflow-y: auto;
}

.detail-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 20px;
}

.comments-list {
  margin-bottom: 20px;
}

.comment-item {
  background-color: #fff5e9;
  padding: 20px;
  border-radius: 10px;
  margin-bottom: 20px;
  display: flex;
  align-items: flex-start;
  transition: all 0.3s ease;
}

.comment-item:hover {
  background-color: #fcc482;
  box-shadow: 0 4px 8px rgb(255, 245, 233);
}

.detail-chat-input {
  display: flex;
  align-items: center;
  padding: 20px;
  background-color: #f8f9fa;
  border-top: 1px solid #eee;
  border-radius: 10px;
}

.input-box {
  flex: 1;
  padding: 12px;
  font-size: 1.2rem;
  height: 60px;
  border: 1px solid #fff5e9;
  border-radius: 30px;
  margin-right: 20px;
  transition: border-color 0.3s ease;
}

.input-box:focus {
  outline: none;
  border-color: #ee9b34;
}

.send-btn {
  padding: 8px 16px;
  font-size: 1.2rem;
  height: 60px;
  width: 120px;
  background-color: #f5a139;
  color: #fff;
  border: none;
  border-radius: 30px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.send-btn:hover {
  background-color: #f89c29;
}

.close-area {
  cursor: pointer;
}
</style>  